/**
 * 将选中区域进行截图，截图完成后调用指定委托函数，(修复支持插入的图片及图表截图)：ALAN-JI
 * @param {Object} options 可选参数
 * @param {Object | String} options.range 选区范围，只能为单个选区；默认为当前选区
 * @param {function} action 委托执行函数，当所有绘图完成后，执行此委托函数（委托函数中可用于触发图片打印，或图片显示）
 */
export function getScreenshotNew(action, options = {}) {
    let {
        range = Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1],
    } = { ...options }
 
    if (getObjType(range) == 'string') {
        if (!formula.iscelldata(range)) {
            return tooltip.info("The range parameter is invalid.", "");
        }
 
        let cellrange = formula.getcellrange(range);
        range = {
            "row": cellrange.row,
            "column": cellrange.column
        };
    }
 
    if (getObjType(range) != 'object' || range.row == null || range.column == null) {
        return tooltip.info("The range parameter is invalid.", "");
    }
 
    let str = range.row[0],
        edr = range.row[1],
        stc = range.column[0],
        edc = range.column[1];
 
    let has_PartMC = hasPartMC(Store.config, str, edr, stc, edc);
 
    if (has_PartMC) {
        return tooltip.info('Cannot perform this operation on partially merged cells', '');
    }
 
    let visibledatarow = Store.visibledatarow;
    let visibledatacolumn = Store.visibledatacolumn;
 
    let scrollHeight, rh_height;
    if (str - 1 < 0) {
        scrollHeight = 0;
        rh_height = visibledatarow[edr];
    }
    else {
        scrollHeight = visibledatarow[str - 1];
        rh_height = visibledatarow[edr] - visibledatarow[str - 1];
    }
 
    //根据当前分辨率计算出A4纸宽度，高度（高度不用限制，默认会自动分页）
    let a4Size=calculateA4PaperSize();
    let scrollWidth, ch_width=a4Size.width;
    if (stc - 1 < 0) {
        scrollWidth = 0;
        ch_width = visibledatacolumn[edc]<a4Size.width ? visibledatacolumn[edc]:a4Size.width;
    }
    else {
        scrollWidth = visibledatacolumn[stc - 1];
        ch_width = visibledatacolumn[edc] - visibledatacolumn[stc - 1]<a4Size.width ? visibledatacolumn[edc] - visibledatacolumn[stc - 1]:a4Size.width;
    }
 
    let newCanvas = $("<canvas>").attr({
        width: Math.ceil(ch_width * Store.devicePixelRatio),
        height: Math.ceil(rh_height * Store.devicePixelRatio)
    }).css({ width: ch_width, height: rh_height });
 
    luckysheetDrawMain(scrollWidth, scrollHeight, ch_width, rh_height, 1, 1, null, null, newCanvas);
    
    let ctx_newCanvas = newCanvas.get(0).getContext("2d");
 
    //补上 左边框和上边框
    ctx_newCanvas.beginPath();
    ctx_newCanvas.moveTo(
        0,
        0
    );
    ctx_newCanvas.lineTo(
        0,
        Store.devicePixelRatio * rh_height
    );
    ctx_newCanvas.lineWidth = Store.devicePixelRatio * 2;
    ctx_newCanvas.strokeStyle = luckysheetdefaultstyle.strokeStyle;
    ctx_newCanvas.stroke();
    ctx_newCanvas.closePath();
 
    ctx_newCanvas.beginPath();
    ctx_newCanvas.moveTo(
        0,
        0
    );
    ctx_newCanvas.lineTo(
        Store.devicePixelRatio * ch_width,
        0
    );
    ctx_newCanvas.lineWidth = Store.devicePixelRatio * 2;
    ctx_newCanvas.strokeStyle = luckysheetdefaultstyle.strokeStyle;
    ctx_newCanvas.stroke();
    ctx_newCanvas.closePath();
    
    //获取插入图片的元素，并在canvas上进行绘制
    if ($('#luckysheet-image-showBoxs')) {
        var imgs = $('#luckysheet-image-showBoxs img');
        imgs.each(function (i) {
            var parent = $(this).parent().parent();
            var left = parent.css("left").replace('px', '');
            var top = parent.css("top").replace('px', '');
            var width = parent.css("width").replace('px', '');
            var height = parent.css("height").replace('px', '');
            var img = new Image()
            img.src = $(this).attr("src");
            ctx_newCanvas.drawImage(img, left, top, width, height);
        });
    }
    //获取统计图元素，并在canvas上进行绘制
    let targetDoms = document.querySelectorAll('.luckysheet-modal-dialog.luckysheet-modal-dialog-chart.luckysheet-data-visualization-chart');
    var chartCount = 0;
    if (targetDoms && targetDoms.length > 0)
    {
        repaintChartScreenshot(newCanvas,ctx_newCanvas,targetDoms,action,0,targetDoms.length);
    }
    
    if (!targetDoms || targetDoms.length == 0) {
        if (action) {
            action(newCanvas.get(0).toDataURL("image/png", 1));
        }
    }
}
 
/**
 * 递归获取所有统计图，并重绘chart到截屏图上：ALAN-JI
 * @param {object} newCanvas canvas画布元素对象
 * @param {object} ctx_newCanvas 当前画布用于绘制新图的对象
 * @param {NodeListOf} targetDoms 所有统计图Nodes集合
 * @param {function} action 委托函数，当所有绘图完成后，执行此委托函数（委托函数中可用于触发图片打印，或图片显示）
 * @param {int} index 当前统计图下标
 * @param {int} length 统计图总集合长度
 */
export function repaintChartScreenshot(newCanvas,ctx_newCanvas,targetDoms,action,index,length) {
    let targetDom = targetDoms[index];
    var left = targetDom.style.left.replace('px', '');
    var top = targetDom.style.top.replace('px', '');
    var width = targetDom.style.width.replace('px', '');
    var height = targetDom.style.height.replace('px', '');
 
    // 此处是实现滚动元素长截图的关键 start
    let copyDom = targetDom.cloneNode(true)
    copyDom.setAttribute('id', 'copyDom')  // 更改id 避免与targetDom id重复
    copyDom.style.width = targetDom.scrollWidth + 'px'
    copyDom.style.height = targetDom.scrollHeight + 'px'
    var chartCanvas = targetDom.getElementsByTagName("canvas")[0];
    var canvasToImg = new Image();
    canvasToImg.src = chartCanvas.toDataURL('image/png', 1);
    canvasToImg.style = chartCanvas.style;
    copyDom.innerHTML = copyDom.innerHTML.replace(chartCanvas.outerHTML, canvasToImg.outerHTML)
    copyDom.style.zIndex=-50
    document.querySelector('body').appendChild(copyDom);
    // 此处是实现滚动元素长截图的关键 end
 
    /* 
    *如不需要长截图，或者要截取的元素无滚动即完全显示。
    *下方要截取的元素改为targetDom,并把copyDom相关代码删除即可 
    */
    // html2canvas截屏，屏幕有滚动条时截图为空
    html2canvas(copyDom, {
        backgroundColor: "transparent",
        allowTaint: true,
        useCORS: true,
        scale: window.devicePixelRatio * 3,
        logging: false,
        imageTimeout: 15000,
        removeContainer: true,
    }).then(canvas => {
        var chartImg = new Image()
        chartImg.src = canvas.toDataURL('image/png', 1);
        document.querySelector('body').removeChild(copyDom)
        chartImg.onload = function () {
            index++;
            ctx_newCanvas.drawImage(chartImg, left, top, width, height);
            if (index >= length && action) {
                action(newCanvas.get(0).toDataURL("image/png", 1));
            }
            else
            {
                //递归调用重绘图片
                repaintChartScreenshot(newCanvas,ctx_newCanvas,targetDoms,action,index,length);
            }
        }
    });
}